package netty.rpc.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import netty.rpc.server.RpcResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2022/5/17 8:43
 */
public class NettyRpcTimeOutResponseHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LogManager.getLogger(NettyRpcTimeOutResponseHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcResponse response = (RpcResponse) msg;
        long now = System.currentTimeMillis();
        long timeOutTime = NettyRpcRequestTimeHolder.timeOutTime(response.getRequestId());
        logger.debug("now : "+ now + " timeOutTime: " + timeOutTime +" requestId: " + response.getRequestId());
        if ( now > timeOutTime ){
            response.setTimeout(true);
            NettyRpcRequestTimeHolder.remove(response.getRequestId());
            logger.error("time out response :{}",response);
        }
        ctx.fireChannelRead(response);
    }
}
